package com.sharding.demo.controller;

import com.sharding.demo.config.CloudHintShardingAlgorithm;
import com.sharding.demo.config.HintType;
import com.sharding.demo.config.HitManagerConfig;
import com.sharding.demo.entity.Student;
import com.sharding.demo.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    private HitManagerConfig hitManagerConfig;

    @Autowired
    private StudentService studentService;


    @PostMapping("/save")
    public String save(@RequestBody Student student) {
        hitManagerConfig.initShardingSphere("111111");

        try{
            studentService.findAll();
            studentService.save(student);
        }catch (Exception e){
           log.error("异常",e);
        }finally {
            //每次执行完sql，执行hintManager.close()，防止自动关闭失败
            hitManagerConfig.closeShardingSphere();
        }
        return "success";
    }

    @GetMapping("/findAll")
    public List<Student> findAll() {
        hitManagerConfig.initShardingSphere("111111");


        List<Student> studentList = studentService.findAll();

        hitManagerConfig.closeShardingSphere();

        return studentList;
    }
}
